package com.wish.wishsystem_management.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wish.wishsystem_management.entity.SysRoleMenu;
import com.wish.wishsystem_management.mapper.SysRoleMenuMapper;
import com.wish.wishsystem_management.service.ISysRoleMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 角色与菜单对应关系 服务实现类
 * </p>
 *
 * @author zhaiwj
 * @since 2021-03-22
 */
@Service
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements ISysRoleMenuService {

    /**
     * 根据角色id删除中间表
     */
    @Override
    public void deleteByRoleId(Long roleId) {
        baseMapper.deleteByRoleId(roleId);
    }

    /**
     * 根据角色id获取菜单id
     *
     * @param roleId
     * @return
     */
    @Override
    public List<Long> queryMenuIdList(Long roleId) {
        List<Long> menuIdList = new ArrayList<>();
        QueryWrapper<SysRoleMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", roleId);
        List<SysRoleMenu> roleMenuList = this.list(queryWrapper);
        for (SysRoleMenu roleMenu : roleMenuList) {
            menuIdList.add(roleMenu.getMenuId());
        }
        return menuIdList;
    }

    @Override
    public void updateRoleMenu(Long roleId, List<Long> menuIdList) {

        //先根据角色id删除
        QueryWrapper<SysRoleMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", roleId);
        this.remove(queryWrapper);

        //保存角色和菜单的关系
        if (menuIdList != null && menuIdList.size() > 0) {
            for (Long menuId : menuIdList) {
                SysRoleMenu sysRoleMenu = new SysRoleMenu();
                sysRoleMenu.setRoleId(roleId);
                sysRoleMenu.setMenuId(menuId);
                this.save(sysRoleMenu);
            }
        }
    }
}
